<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Editor</title>
    <link rel="stylesheet" href="toastui-editor.min.css">
</head>

<body>
    <!-- Create the editor container -->
    <div id="editor"></div>

    <!-- Include the Quill library -->
    <script src="toastui-editor-all.min.js"></script>

    <!-- Initialize Quill editor -->
    <script>
        var mdText = "";
        const editor = new toastui.Editor({
            el: document.querySelector('#editor'),
            previewStyle: 'vertical',
            height: '580px',
            initialEditType: 'wysiwyg',
            initialValue: ""
        });
        function getMarkdownText() {
            return editor.getMarkdown();
        }
        function postMsg() {
            window.chrome.webview.postMessage(mdText);
            console.log(mdText);
        }
        function setHeight(height){
            editor.setHeight(height)
        }
        function setMarkdown(msg){
            let utf8String = base64DecodeToUtf8(msg);
            editor.setMarkdown(utf8String, false)
        }
        function base64DecodeToUtf8(base64String) {
            let binaryString = atob(base64String);
            let len = binaryString.length;
            let bytes = new Uint8Array(len);
            for (let i = 0; i < len; i++) {
                bytes[i] = binaryString.charCodeAt(i);
            }
            return new TextDecoder('utf-8').decode(bytes);
        }
        
        setInterval(function () {
            let currMd = getMarkdownText();
            if (currMd != mdText) {
                mdText = currMd;
                postMsg();
            }
        }, 500);
    </script>
</body>

</html>